package com.it.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.util.SaResult;
import com.github.pagehelper.PageInfo;
import com.it.annotation.ClearCache;
import com.it.annotation.SystemLog;
import com.it.bean.Role;
import com.it.dto.RoleDTO;
import com.it.page.PageImpl;
import com.it.page.PageQuery;
import com.it.service.RoleService;
import com.it.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/role")
public class RoleController {

    private final RoleService roleService;

    @PostMapping("/page")
    @Cacheable(cacheNames = "roles", key = "T(java.util.Objects).hash(#pageQuery.page, #pageQuery.pageSize, #pageQuery.queryBody)")
    public SaResult page(@RequestBody PageQuery<RoleDTO> pageQuery) {
        PageInfo<RoleVo> pageInfo = roleService.page(pageQuery);
        return SaResult.data(PageImpl.of(pageInfo));
    }

    @PostMapping("/list")
    @Cacheable(cacheNames = "roles", key = "T(java.util.Objects).hash(#root.methodName)")
    public SaResult list(@RequestBody Role role) {
        List<Role> roles = roleService.list(role);
        return SaResult.data(roles);
    }

    @ClearCache
    @PostMapping("/save")
    @SystemLog(value = "角色数据", method = "新增修改")
    @CacheEvict(cacheNames = {"roles", "users"}, allEntries = true)
    @SaCheckPermission(value = {"role-add", "role-edit"}, orRole = {"admin"})
    public SaResult save(@RequestBody Role role) {
        roleService.save(role);
        return SaResult.ok();
    }

    @ClearCache
    @PostMapping("/delete/{id}")
    @SystemLog(value = "角色数据", method = "数据删除")
    @CacheEvict(cacheNames = {"roles", "users"}, allEntries = true)
    @SaCheckPermission(value = {"role-delete"}, orRole = {"admin"})
    public SaResult delete(@PathVariable("id") Long id) {
        roleService.delete(id);
        return SaResult.ok();
    }

    @ClearCache
    @PostMapping("/authorized/{roleId}")
    @SaCheckPermission(value = {"role-grant"}, orRole = {"admin"})
    @CacheEvict(cacheNames = {"roles", "users"}, allEntries = true)
    public SaResult authorized(@PathVariable("roleId") Long roleId, @RequestBody List<Long> menuIds) {
        roleService.authorized(roleId, menuIds);
        return SaResult.ok();
    }

    @ClearCache
    @GetMapping("/auths/{roleId}")
    @CacheEvict(cacheNames = {"roles", "users"}, allEntries = true)
    public SaResult auths(@PathVariable("roleId") Long roleId) {
        List<Long> menuIds = roleService.auths(roleId);
        return SaResult.data(menuIds);
    }


}
